<template>
  <div v-loading="loading" class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="备件编码" prop="code">
          <CodeRuleInput
            :band-value.sync="formData.code"
            table-name="device_spare_standing_book"
            column-name="code"
            :is-edit="id"
          />
        </el-form-item>
        <el-form-item label="备件名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="备件类型" prop="type" class="clickChoose">
          <el-input v-model="formData.typeName" placeholder="请选择" readonly />
          <!--          <el-select v-model="formData.type" filterable placeholder="请选择">-->
          <!--            <el-option-->
          <!--              v-for="item in typeTableList"-->
          <!--              :key="item.id"-->
          <!--              :label="item.name"-->
          <!--              :value="item.id"-->
          <!--            />-->
          <!--          </el-select>-->
          <a class="clickChoose_button" @click.prevent="chooseTypes">
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input v-model="formData.model" placeholder="请输入" clearable />
        </el-form-item>
        <!-- <el-form-item label="品牌">
          <el-input v-model="formData.brand" placeholder="请输入" clearable />
        </el-form-item> -->
        <el-form-item label="备件供应商" class="clickChoose">
          <el-input v-model="formData.supplierName" placeholder="请选择" readonly />
          <!--          <el-select v-model="formData.supplier" clearable filterable placeholder="请选择">-->
          <!--            <el-option-->
          <!--              v-for="item in supplierTableList"-->
          <!--              :key="item.id"-->
          <!--              :label="item.name"-->
          <!--              :value="item.id"-->
          <!--            />-->
          <!--          </el-select>-->
          <a class="clickChoose_button" @click.prevent="chooseSuppliers">
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="备件单位">
          <DictSelect :band-value.sync="formData.numberUnitCode" dict-type="sparePartsUnit" />
        </el-form-item>
        <el-form-item label="备件单价(元)" prop="price">
          <el-input v-model="formData.price" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="安全库存" prop="safeInventory">
          <el-input v-model="formData.safeInventory" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="采购周期" prop="purchasePeriod">
          <el-input v-model="formData.purchasePeriod" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="采购周期单位">
          <DictSelect :band-value.sync="formData.purchasePeriodUnitCode" dict-type="purchasePeriodUnitCode" />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入" maxlength="200" show-word-limit />
        </el-form-item>
        <!--        <el-form-item v-if="isShow" style="margin-top:-5px;" label="状态">-->
        <!--          <el-switch-->
        <!--            v-model="formData.status"-->
        <!--            :active-value="1"-->
        <!--            :inactive-value="0"-->
        <!--            active-color="#13ce66"-->
        <!--            inactive-color="#999999"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item v-if="isShow" label="状态" style="margin-top:-5px;">
          <el-radio-group v-model="formData.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备件配图" class="double">
          <pictureUpload
            :file-names="formData.avatar"
            :file-real-names="formData.avatar"
            :file-urls="formData.avatarUrl"
            :row-index="1"
            single-multiple="single"
            @fileName="setFileName2"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo } from '@/api/equipmentManage/sparePart/standingBook'
import { list as typeList } from '@/api/equipmentManage/sparePart/type'
import { list as supplierList } from '@/api/equipmentManage/sparePart/supplier'
import chooseType from '../sparePartsType/chooseType.vue'
import chooseSupplier from '../sparePartsSuppliers/chooseSuppliers.vue'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    const validateSafeInventory = (rule, value, callback) => {
      if (value && !this.SETTINGS.reg_integer.test(value)) {
        callback(new Error('安全库存必须为整数'))
      } else {
        callback()
      }
    }
    const validatePurchasePeriod = (rule, value, callback) => {
      if (value && !this.SETTINGS.reg_integer.test(value)) {
        callback(new Error('采购周期必须为整数'))
      } else {
        callback()
      }
    }
    const validatePrice = (rule, value, callback) => {
      if (value && !this.SETTINGS.reg_zero.test(value)) {
        callback(new Error('备件单价未正确填写'))
      } else {
        callback()
      }
    }
    return {
      loading: true,
      isShow: false,
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        type: undefined,
        typeName: undefined,
        model: undefined,
        brand: undefined,
        supplier: undefined,
        supplierName: undefined,
        numberUnitCode: undefined,
        price: undefined,
        safeInventory: undefined,
        purchasePeriod: undefined,
        purchasePeriodUnitCode: undefined,
        avatar: '',
        avatarRealName: '',
        avatarUrl: '',
        status: '1',
        remark: undefined,
        weightedAveragePrice: ''
      },
      pageData: {
        companyName: undefined,
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        status: 1,
        isAsc: 'desc'
      },
      supplierTableList: [],
      typeTableList: [],
      num: 1,
      roleOptions: [],
      rules: {
        name: [
          { required: true, message: '备件名称不能为空', trigger: 'change' }
        ],
        code: [
          { required: true, message: '备件编码不能为空', trigger: 'blur' }
        ],

        type: [
          { required: true, message: '备件类型不能为空', trigger: 'change' }
        ],
        price: [
          { validator: validatePrice, trigger: 'change' }
        ],
        safeInventory: [
          { validator: validateSafeInventory, trigger: 'change' }
        ],
        purchasePeriod: [
          { validator: validatePurchasePeriod, trigger: 'change' }
        ]
      }
    }
  },
  created() {
    if (!this.id) { // 没有id就是新增
      this.loading = false
      Object.keys(this.defaultValue).forEach(key => { // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
    this.getSupplierList()
    this.getTypeList()
  },
  methods: {
    // 校验整数
    // onlyInteger(e) {
    //   console.log(111)
    //   const rule = /^[0-9][0-9]*$/
    //   const num = Number(e)
    //   if (rule.test(e)) {
    //     this.formData.purchasePeriod = e
    //   } else if (e && num !== 0) {
    //     this.$message.warning('采购周期必须为整数')
    //     this.formData.purchasePeriod = e.replace('.', '')
    //   }
    // },
    // 校验整数
    // onlyInteger2(e) {
    //   console.log(111)
    //   const rule = /^[0-9][0-9]*$/
    //   const num = Number(e)
    //   if (rule.test(e)) {
    //     this.formData.safeInventory = e
    //   } else if (e && num !== 0) {
    //     this.$message.warning('采购周期必须为整数')
    //     this.formData.safeInventory = e.replace('.', '')
    //   }
    // },
    // 查询供应商列表
    getSupplierList() {
      supplierList(this.pageData).then(res => {
        this.supplierTableList = res.data
      })
    },
    // 查询备件类型列表
    getTypeList() {
      typeList(this.pageData).then(res => {
        this.typeTableList = res.data
      })
    },
    getInfo() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.formData.status += ''
        this.isShow = true
        this.loading = false
      })
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    // 校验两位小数
    // haveTwoDecimalPlaces(e) {
    //   if (e.indexOf('.') > -1) {
    //     const afterPoint = e.split('.')
    //     if (afterPoint[1].length > 2) {
    //       this.formData.price = e.slice(0, e.indexOf('.') + 3)
    //       this.$message.warning('至多可输入两位小数')
    //     }
    //   } else {
    //     this.formData.price = e
    //   }
    // },

    // 选择备件类型
    chooseTypes() {
      this.$layer.iframe({// 弹框
        content: {
          content: chooseType, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: this.formData.type ? this.formData.type : ''
          }// props
        },
        area: ['880px', '570px'],
        title: '选择备件类型', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 选择备件供应商
    chooseSuppliers() {
      this.$layer.iframe({// 弹框
        content: {
          content: chooseSupplier, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: this.formData.supplier ? this.formData.supplier : ''
          }// props
        },
        area: ['880px', '570px'],
        title: '选择备件供应商', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    showType(data) {
      this.formData.type = data.id
      this.formData.typeName = data.name
      this.getTypeList()
    },
    showSupplier(data) {
      this.formData.supplier = data.id
      this.formData.supplierName = data.name
      this.getSupplierList()
    },
    setFileName2(...data) {
      this.formData.avatar = data[0]
      this.formData.avatarRealName = data[1]
      this.formData.avatarUrl = data[2]
    }
  }
}
</script>

<style lang="less" scoped>
</style>
